[#include "../../../common/html.ftl" /]
[@html]
    [@head title="选择用户" css=["fw", "bootstrap-table"] /]
    [@body]
        [@main ]
            <div class="fw-tables">
                [@searchForm searchId="form-user-search" display="block" ]
                    <input id="deptTreeId" name="deptId" type="hidden"/>
                    <div class="am-form-group">
                        <input type="text" name="loginName" class="am-form-field am-input-sm am-radius"
                               placeholder="登录账号">
                    </div>
                    <div class="am-form-group">
                        <input type="text" name="userName" class="am-form-field am-input-sm am-radius"
                               placeholder="用户姓名">
                    </div>
                    <div class="am-form-group">
                        <input  id="deptTreeName" type="text" name="deptName" class="am-form-field am-input-sm am-radius"
                               placeholder="部门名称" onclick="choiceDeptTree('33','deptTreeId','deptTreeName')">
                    </div>
                    <div class="am-form-group">
                        <select name="status" class="am-radius" data-am-selected placeholder="用户状态">
                            <option value=""></option>
                            [#list dict.getType("sys_status") as dict]
                                <option value="${dict.dictValue}">${dict.dictLabel}</option>
                            [/#list]
                        </select>
                    </div>
                [/@searchForm]

                <div class="fw-table">
                    <div id="tip_" class="am-radius graytip" style="width: 100%;height: 25px;line-height:25px;background-color: lemonchiffon;margin-bottom: 5px;">
                        <div class="check_all" style="display: none;text-align: center;">
                            已勾选&nbsp;<span class="selected_num">0</span>&nbsp;名人员，
                            <a onclick="checkPersonnelBatch('all_select');">勾选 "人员列表" 中全部&nbsp;<span class="all_num">0</span>&nbsp;名人员</a>
                        </div>
                        <div class="uncheck_all" style="display: none;text-align: center;">
                            已勾选&nbsp;<span class="selected_num">0</span>&nbsp;名人员，
                            <a onclick="uncheckPersonnelBatch('all_select');">取消勾选</a>
                        </div>
                    </div>
                    <div style="width: 100%;height: calc(100% - 25px);">
                        <div class="select-left" style="width: 50%;height: 100%;float: left;">
                            <div class="" style="width: 100%;">
                                <div class="am-text-primary "><span class="am-icon-user-plus"><b> 请选择人员</b></span></div>
                            </div>
                            <table id="bootstrap-table" class="am-table am-table-bordered" data-mobile-responsive="true"></table>
                        </div>
                        <div class="select-center" style="width: 50px;height: 100%;padding: 0px 5px;float: left;">
                            <div class="am-text-center" style="margin-top: 105px;">
                                <button class="am-btn am-btn-block am-btn-default am-icon-angle-double-right"></button>
                                <button class="am-btn am-btn-block am-btn-default am-icon-angle-double-left am-margin-top-xs"></button>
                            </div>
                        </div>
                        <div class="select-right" style="width: calc(50% - 50px);height: 100%;float: left;">
                            <div class="layui-transfer-header" style="width: 100%;">
                                <div class="am-text-primary"><span class="am-icon-users"><b> 已选择人员</b></span></div>
                            </div>
                            <table id="bootstrap-table-selected" class="am-table am-table-bordered" data-mobile-responsive="true"></table>
                        </div>
                    </div>
                </div>

            </div>
        [/@main]

        [@rightToolbar /]

        [@script js=["fw", "bootstrap-table", "ztree-ajax"]]
            <script type="text/javascript">
                // 人员状态
                var datasStatus = ${convert.toJson(dict.getType("sys_status"))};
                var datasSex = ${convert.toJson(dict.getType("sys_user_sex"))};
                // 库中已选择的人员
                var userSelected = ${convert.toJson(userSelected)};
                // 是否单选、复选标识（1-单选，2-复选）
                var select_type = "${selectType!'1'}";
                var is_exclude_selected = "${isExcludeSelected!'0'}";
                var isRadio = select_type == '1' ? true : false;
                var isCheckbox = select_type == '2' ? true : false;
                // 排除的人员数据编号
                var exclude_userIds = [];
                // 当前选择人员的数据编号
                var select_userIds = [];
                // 当前选择人员的姓名
                var select_loginNames = [];
                // 当前选择人员的姓名
                var select_userNames = [];
                // 可选择总数
                var total_num = 0;

                if (is_exclude_selected == '1' && userSelected != null && userSelected.length > 0) {
                    $.each(userSelected, function (i, row) {
                        exclude_userIds[i] = row.userId;
                    });
                }

                // 声明指定删除行对象
                function Row(userId, loginName, userName) {
                    this.userId = userId;
                    this.loginName = loginName;
                    this.userName = userName;
                }

                // 请求前缀
                var prefix = ctx + "osfw/system/manage/user";

                $(function () {
                    if(isRadio){
                        $("#tip_").hide();
                    }

                    // 默认权限参数初始化选择
                    defaultPermissionsQueryParams();

                    var options = {
                        id: "bootstrap-table",
                        url: prefix + "/userList",
                        modalName: "人员选择",
                        uniqueId: "userId",
                        showSearch: false,
                        showRefresh: false,
                        showToggle: false,
                        showColumns: false,
                        pageList: [],
                        pageSize: 5,
                        striped: false,
                        classes: "table table-hover table-custom",     // 样式相关
                        clickToSelect: true,
                        rememberSelected: true,
                        queryParams: queryParams,
                        height: 302,
                        columns: [
                            {
                                checkbox: isCheckbox,
                                radio: isRadio,
                                formatter: function (value, row, index) {
                                    if (select_userIds.length > 0 && $.inArray(row.userId, select_userIds) != -1) {
                                        return {
                                            //设置选中（翻页时默认选中之前已选中的数据行）
                                            checked: true,
                                        };
                                    }
                                }
                            },
                            {
                                field: 'userId',
                                title: '编号',
                                visible: false
                            },
                            {
                                field: 'loginName',
                                title: '账号',
                                visible: false,
                            },
                            {
                                field: 'userName',
                                title: '姓名'
                            },
                            {
                                field: 'sex',
                                title: '性别',
                                formatter: function (value, row, index) {
                                    return $.table.selectDictLabel(datasSex, value);
                                }
                            },
                            {
                                field: 'deptName',
                                title: '部门',
                                formatter: function (value, row, index) {
                                    return $.table.tooltip(value, 10);
                                }
                            },
                            {
                                field: 'status',
                                title: '状态',
                                formatter: function (value, row, index) {
                                    return $.table.tooltipDict(datasStatus, value, 2);
                                }
                            }
                        ]
                    };
                    $.table.init(options);

                    $("#bootstrap-table-selected").bootstrapTable({
                        modalName: "已选择人员",
                        showSearch: false,
                        showRefresh: false,
                        showToggle: false,
                        showColumns: false,
                        uniqueId: 'userId',
                        clickToSelect: true,
                        rememberSelected: true,
                        pageList: [],
                        pageSize: 5,
                        sidePagination: "client",
                        iconSize: 'outline',
                        pagination: true,
                        toolbar: "toolbar",
                        classes: "table table-hover table-custom",     // 样式相关
                        striped: false,
                        escape: false,
                        showFooter: false,
                        search: false,
                        showPageGo: false,
                        showExport: false,
                        fixedColumns: false,
                        fixedNumber: 0,
                        rightFixedColumns: false,
                        rightFixedNumber: 0,
                        sortName: "orderNum",
                        sortOrder: "asc",
                        height: 302,
                        columns: [
                            {
                                field: 'userId',
                                title: '编号',
                                visible: false
                            },
                            {
                                field: 'loginName',
                                title: '账号',
                                visible: false
                            },
                            {
                                field: 'userName',
                                title: '姓名'
                            },
                            {
                                field: 'sex',
                                title: '性别',
                                formatter: function (value, row, index) {
                                    return $.table.selectDictLabel(datasSex, value);
                                }
                            },
                            {
                                field: 'deptName',
                                title: '部门',
                                formatter: function (value, row, index) {
                                    return $.table.tooltip(value, 7);
                                }
                            },
                            {
                                field: 'status',
                                title: '状态',
                                formatter: function (value, row, index) {
                                    return $.table.tooltipDict(datasStatus, value, 2);
                                }
                            },
                            {
                                title: '操作',
                                align: 'left',
                                formatter: function(value, row, index) {
                                    var actions = [];
                                    actions.push('<a class="am-btn am-btn-danger am-icon-remove" style="font-size: .8rem;" title="取消选择" href="javascript:void(0)" onclick="deletePersonnel(\'' + row.userId + '\',\''+row.loginName+'\',\''+row.userName+'\')"></a>');
                                    return actions.join('');
                                }
                            }
                        ]
                    });

                    // 成功加载远程数据
                    $('#bootstrap-table').on('load-success.bs.table', function (e, data) {
                        total_num = data.total;
                        if (is_exclude_selected == '0' && userSelected != null && userSelected.length > 0) {
                            var arr = [];
                            $.each(userSelected, function (i, row) {
                                arr[i] = row.userId;
                                checkPersonnel(row);
                            });
                            $('#bootstrap-table').bootstrapTable('checkBy', {field: 'userId', values: arr});
                            if(select_userIds.length == userSelected.length){
                                userSelected.length = 0;
                            }
                        }
                    });

                    // 点击选中行
                    $('#bootstrap-table').on('check.bs.table', function (e, row) {
                        checkPersonnel(row);
                    });

                    // 取消选中行
                    $('#bootstrap-table').on('uncheck.bs.table', function (e, row) {
                        uncheckPersonnel(row);
                    });

                    // 当前页面批量选择/批量取消选择
                    $('input[name="btSelectAll"]').on('click', function () {
                        // 判断是当前页面批量选择还是取消选择
                        var checked = $('input[name="btSelectAll"]').prop("checked");
                        if (checked) {
                            // 当前页面批量选择
                            checkPersonnelBatch("page_select");
                        } else {
                            // 当前页面批量取消选择
                            uncheckPersonnelBatch("page_select");
                        }
                    });

                    if(!isPC()){
                        $(".select-left").css("width","340px");
                        $(".select-center").hide();
                        $(".select-right").hide();
                    }

                });

                function queryParams(params) {
                    var search = $.table.queryParams(params);
                    if (is_exclude_selected == '1' && exclude_userIds.length > 0) {
                        search.userIds = exclude_userIds.join(",");
                    }
                    return search;
                }

                // 默认查询条件
                function defaultPermissionsQueryParams() {
                    // 默认查询条件：姓名、身份证号码
                    var loginName = "${sysUser.loginName!''}";
                    var userName = "${sysUser.userName!''}";
                    $("input[name='loginName']").val(loginName);
                    $("input[name='userName']").val(userName);
                    // 默认查询条件：所属部门
                    var deptId = "${sysUser.deptId!''}";
                    var deptName = "${sysUser.deptName!''}";
                    if (deptId != '') {
                        $("#deptTreeId").val(deptId);
                        $("#deptTreeName").val(deptName);
                    }
                }

                // 表单重置回调函数
                function formResetCallBlack() {
                    var userName = "${sysUser.userName!''}";
                    var loginName = "${sysUser.loginName!''}";
                    var deptId = "${sysUser.deptId!''}";
                    var deptName = "${sysUser.deptName!''}";
                    $("input[name='userName']").val(userName);
                    $("input[name='loginName']").val(loginName);
                    $("#deptTreeId").val(deptId);
                    $("#deptTreeName").val(deptName);
                }

                // 选择
                function checkPersonnel(row) {
                    if (row != null && row != undefined) {
                        if ($.inArray(row.userId, select_userIds) == -1) {
                            // 判断是否为单选
                            if(isRadio) {
                                $("#bootstrap-table-selected").bootstrapTable('removeAll');
                                $("#bootstrap-table-selected").bootstrapTable('insertRow', {
                                    index: 0,
                                    row: {
                                        userId: row.userId,
                                        loginName: row.loginName,
                                        userName: row.userName,
                                        sex: row.sex,
                                        deptName: row.deptName,
                                        status: row.status
                                    }
                                });
                                // 已选择容器中添加已选择人员信息
                                select_userIds[0] = row.userId;
                                select_loginNames[0] = row.loginName;
                                select_userNames[0] = row.userName;
                            } else {
                                // 获取已选择列表长度作为新插入数据下标
                                var index = $("#bootstrap-table-selected").bootstrapTable('getData').length;
                                $("#bootstrap-table-selected").bootstrapTable('insertRow', {
                                    index: index,
                                    row: {
                                        userId: row.userId,
                                        loginName: row.loginName,
                                        userName: row.userName,
                                        sex: row.sex,
                                        deptName: row.deptName,
                                        status: row.status
                                    }
                                });
                                // 已选择容器中添加已选择人员信息
                                select_userIds.push(row.userId);
                                select_loginNames.push(row.loginName);
                                select_userNames.push(row.userName);
                            }
                            // 选择提示
                            grayTip();
                        }
                    }
                }

                // 取消选择
                function uncheckPersonnel(row) {
                    if (row != null && row != undefined) {
                        //去掉已选择列表中的数据
                        var removeIds = [];
                        removeIds.push(row.userId);
                        $("#bootstrap-table-selected").bootstrapTable('remove', {
                            field: 'userId',
                            values: removeIds
                        });
                        if (select_userIds.length > 0) {// 人员编号
                            for (var n = 0; n < select_userIds.length; n++) {
                                if (select_userIds[n] != undefined && row.userId == select_userIds[n]) {
                                    delete select_userIds[n]; // 删除元素并已undefined代替（方法固有）
                                }
                            }
                        }
                        if (select_loginNames.length > 0) {// 登录账号
                            for (var n = 0; n < select_loginNames.length; n++) {
                                if (select_loginNames[n] != undefined && row.loginName == select_loginNames[n]) {
                                    delete select_loginNames[n]; // 删除元素并已undefined代替（方法固有）
                                }
                            }
                        }
                        if (select_userNames.length > 0) {// 登录账号
                            for (var n = 0; n < select_userNames.length; n++) {
                                if (select_userNames[n] != undefined && row.userName == select_userNames[n]) {
                                    delete select_userNames[n]; // 删除元素并已undefined代替（方法固有）
                                }
                            }
                        }
                    }
                    // 过滤掉因为delete 删除产生的undefined元素
                    select_userIds = select_userIds.filter(function (item) {
                        return item != undefined;
                    });
                    // 过滤掉因为delete 删除产生的undefined元素
                    select_loginNames = select_loginNames.filter(function (item) {
                        return item != undefined;
                    });
                    // 过滤掉因为delete 删除产生的undefined元素
                    select_userNames = select_userNames.filter(function (item) {
                        return item != undefined;
                    });
                    // 选择提示
                    grayTip();
                }

                // 批量选择
                function checkPersonnelBatch(tag) {
                    if (tag == "page_select") {
                        // 获取当前页所有行，并勾选所有
                        var rows = $("#bootstrap-table").bootstrapTable('getSelections');
                        $.each(rows, function (i, row) {
                            checkPersonnel(row);
                        });
                    } else if (tag == "all_select") {
                        // 获取全部人员并勾选所有
                        $.ajax({
                            type: "POST",
                            url: prefix + "/userListAll",
                            data: $("#personnelSelection-form").serializeArray(),
                            async: false,
                            success: function (rows) {
                                $.each(rows.data, function (i, row) {
                                    checkPersonnel(row);
                                });
                            }
                        });
                        $.table.refresh();
                    }
                }

                // 批量取消选择
                function uncheckPersonnelBatch(tag) {
                    if (tag == "page_select") {
                        // 清除当前页所有选择
                        var rows = $("#bootstrap-table").bootstrapTable('getData');
                        $.each(rows, function (i, row) {
                            uncheckPersonnel(row);
                        });
                    } else if (tag == "all_select") {
                        // 清除所有选择
                        $("#bootstrap-table-selected").bootstrapTable('removeAll');
                        select_userIds.length = 0;
                        select_loginNames.length = 0;
                        select_userNames.length = 0;
                        $.table.refresh();
                        // 选择提示
                        grayTip();
                    }
                }

                // 已选择人员列表取消指定人员选择
                function deletePersonnel(userId, loginName, userName) {
                    uncheckPersonnel(new Row(userId, loginName, userName));
                    $.table.refresh();
                }

                // 选择提示
                function grayTip() {
                    var selecteds = select_userIds.length;
                    if (selecteds > 0) {
                        var display_graytip = $('.graytip').css('display');
                        if (display_graytip != 'block') {
                            // $(".graytip").slideDown("slow");
                        }
                        if (selecteds < total_num) {
                            $(".check_all").show();
                            $(".uncheck_all").hide();
                        } else {
                            $(".check_all").hide();
                            $(".uncheck_all").show();
                        }
                        $(".check_all .selected_num").html(selecteds);
                        $(".uncheck_all .selected_num").html(selecteds);
                        $(".check_all .all_num").html(total_num);
                    } else {
                        // $(".graytip").slideUp("slow");
                        $(".check_all").hide();
                        $(".check_all .selected_num").html(0);
                        $(".uncheck_all").hide();
                        $(".uncheck_all .selected_num").html(0);
                        $(".check_all .all_num").html(0);
                    }
                }

                // 确定
                function submitHandler(index, modalo) {
                    if (select_userIds.length == 0) {
                        $.modal.alertWarning("请至少选择一条记录");
                        return;
                    }
                    // 选择控件id
                    var elementId = "${elementId!''}";
                    // 选择的人员编号
                    var userIds = isRadio ? select_userIds[0] : select_userIds.join();
                    // 选择的登录名称
                    var loginNames = isRadio ? select_loginNames[0] : select_loginNames.join();
                    // 选择的人员姓名
                    var userNames = isRadio ? select_userNames[0] : select_userNames.join();

                    // 回调返回：调用控件id，人员ID，登录账号，人员姓名
                    window.parent.selectUsersCallback(elementId, userIds, loginNames, userNames);

                    $.modal.close();
                }

            </script>
        [/@script]
    [/@body]
[/@html]
